package com.googlecode.biglog.intface.http;

import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.common.util.ValueUtils;

import org.apache.commons.collections.map.ListOrderedMap;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HttpController {
	private static final Logger logger = LoggerFactory.getLogger(HttpController.class);

	private static final List<String> METHODS = ValueUtils.toList("info", "debug", "error", "warn");

	@RequestMapping(value = { "/biglog/info", "/biglog/debug", "/biglog/error", "/biglog/warn" }, headers = "Accept=text/html; charset=UTF-8")
	public @ResponseBody
	String invoke(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String uri = request.getRequestURI();

		// strip everything from the first semi-colon
		int pathParamIndex = uri.indexOf(';');
		if (pathParamIndex > 0)
			uri = uri.substring(0, pathParamIndex);

		// strip everything from the first question mark
		int queryParamIndex = uri.indexOf('?');
		if (queryParamIndex > 0)
			uri = uri.substring(0, queryParamIndex);

		int index = uri.lastIndexOf('/');
		String method = index == -1 ? uri : uri.substring(index + 1);

		if (!METHODS.contains(method))
			return "";

		String prefix = request.getParameter("prefix");
		@SuppressWarnings("unchecked")
		Map<String, Object> map = new ListOrderedMap();
		@SuppressWarnings("unchecked")
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			if (name.equals("prefix"))
				continue;
			map.put(name, request.getParameter(name));
		}
		String message = (prefix != null ? prefix : "") + new ObjectMapper().writeValueAsString(map);

		switch (METHODS.indexOf(method)) {
		case 0:
			logger.info(message);
			break;
		case 1:
			logger.debug(message);
			break;
		case 2:
			logger.error(message);
			break;
		case 3:
			logger.warn(message);
			break;
		}

		return "";
	}
}
